package siddur.traktask.chrome.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import siddur.traktask.chrome.model.KeyValueVO;
import siddur.traktask.entity.JobInfo;
import siddur.traktask.entity.TaskInfo;
import siddur.traktask.entity.UserInfo;
import siddur.traktask.framework.Constants;
import siddur.traktask.repository.JobRepository;
import siddur.traktask.repository.TaskRepository;
import siddur.traktask.repository.UserRepository;
import siddur.traktask.util.TaskUtil;

@RestController
@RequestMapping("/app")
public class AppController {
	
	private static final Logger log4j = Logger.getLogger(AppController.class);
	
	@Autowired UserRepository userRep;
	@Autowired JobRepository jobRep;
	@Autowired TaskRepository taskRep;

	/*
	 * only need to input a valid email
	 */
	@RequestMapping(value="/sl", method=RequestMethod.POST)
	public List<KeyValueVO> simpleLogin(@RequestBody String data, HttpSession session){
		String array[] = data.split("\\|\\|\\|");
		String email = array[0];
		String password = null;
		if(array.length == 2){
			password = array[1];
		}
		List<KeyValueVO> results = new ArrayList<>();
		if(StringUtils.isNotBlank(email)){
			UserInfo user = userRep.findOne(email);
			if(user == null){
				log4j.info("create a user: " + email);
				//create a user
				user = new UserInfo();
				user.setEmail(email);
				user.setPassword(password);
				userRep.save(user);
				
				//create a default job
				JobInfo job = new JobInfo();
				job.setName("Default");
				job.setOwner(user);
				jobRep.save(job);
				
				//create a default task
				TaskInfo task = new TaskInfo();
				task.setName("Default");
				task.setJob(job);
				task.setAssignee(user);
				taskRep.save(task);
				String token = TaskUtil.generateToken(task.getId(), task.getCreatedAt().getTime());
				task.setToken(token);
				taskRep.save(task);
				session.setAttribute(Constants.SESSION_USER, user);
				
				KeyValueVO kv = new KeyValueVO(task.getId(), job.getName() + "["+ task.getName() +"]");
				results.add(kv);
			}
			else if(user.isEnable()){
				user = userRep.findOne(email);
				String p = user.getPassword();
				if(StringUtils.isBlank(p) || p.equals(password)){
					session.setAttribute(Constants.SESSION_USER, user);
					List<TaskInfo> tasks = taskRep.findByAssignee(user);
					for (TaskInfo t : tasks) {
						results.add(new KeyValueVO(t.getId(), t.getJob().getName() + "["+ t.getName() +"]"));
					}
				}
			}
		}
		return results;
	}
	
	@RequestMapping("gen_token")
	public String generateToken(@RequestParam("taskId") long taskId){
		long time = (long)(new Date().getTime() * 1.01f);
		String token = TaskUtil.generateToken(taskId, time);
		TaskInfo task = taskRep.findOne(taskId);
		task.setToken(token);
		taskRep.save(task);
		return token;
	}
	
	@RequestMapping("token")
	public String getToken(@RequestParam("taskId") long taskId){
		TaskInfo task = taskRep.findOne(taskId);
		return task.getToken();
	}
}
